package chan.com.mvplib.proxy;

import android.os.Bundle;

import chan.com.mvplib.factory.PresenterMvpFactory;
import chan.com.mvplib.presenter.BaseMvpPresenter;
import chan.com.mvplib.view.BaseMvpView;

/**
 * Created by chen on 2017/12/25.
 */
public class BaseMvpProxy<V extends BaseMvpView, P extends BaseMvpPresenter<V>> implements PresenterProxyInterface<V, P> {
    private static final String PRESENTER_KEY = "presenter_key";

    /**
     * presenter 工厂类
     *
     * @param presenterFactory
     */
    private PresenterMvpFactory<V, P> mFactory;
    private P mPresenter;
    private Bundle mBundle;
    private boolean mIsattachView;

    public BaseMvpProxy(PresenterMvpFactory<V, P> presenterMvpFactory) {
        this.mFactory = presenterMvpFactory;
    }

    @Override
    public void setPresenterFactory(PresenterMvpFactory<V, P> presenterFactory) {
        if (mPresenter != null) {
            throw new IllegalArgumentException("this method is before getMvpPresenter() if presenter is created  that is not be fix");
        }
        this.mFactory = presenterFactory;
    }

    @Override
    public PresenterMvpFactory<V, P> getPresenterFactory() {
        return mFactory;
    }

    @Override
    public P getMvpPresenter() {
        if (mFactory != null) {
            if (mPresenter == null) {
                mPresenter = mFactory.createMvpPresenter();
                mPresenter.onCreatePresenter(mBundle == null ? null : mBundle.getBundle(PRESENTER_KEY));
            }
        }
        return mPresenter;
    }

    /**
     * 处理presenter的生命周期
     *
     */
    /**
     * 绑定presenter 和View
     *
     * @param mvpview
     */
    public void onResume(V mvpview) {
        getMvpPresenter();
        if (mPresenter != null && !mIsattachView) {
            mPresenter.onAttachMvpView(mvpview);
            mIsattachView = true;
        }
    }

    /**
     * 销毁Presenter 持有的view
     */
    private void onDetachMvpView() {
        if (mPresenter != null && mIsattachView) {
            mPresenter.onDetachMvpView();
            mIsattachView = false;
        }
    }

    public void onDestroy() {
        if (mPresenter != null) {
            onDetachMvpView();
            mPresenter.onDestroyPersenter();
            mPresenter = null;
        }
    }


    public Bundle onSaveInstanceState() {
        Bundle bundle = new Bundle();
        getMvpPresenter();
        if (mPresenter != null) {
            Bundle presenterBundle = new Bundle();
            mPresenter.onSaveInstanceState(presenterBundle);
            bundle.putBundle(PRESENTER_KEY, presenterBundle);
        }
        return bundle;
    }

    public void onRestoreInstanceState(Bundle saveInstanceState) {
        this.mBundle = saveInstanceState;
    }

}
